<template>
  <el-form :model="modelValue" :label-width="labelWidth" :size="formSize" ref="form" :rules="formRules">
    <el-row>
      <el-col
        :xs="item.xs || 24"
        :sm="item.sm || 12"
        :md="item.md || 8"
        :lg="item.lg || 6"
        :xl="item.xl || 4"
        v-for="item in formConfig"
        :key="item.name"
      >
        <el-form-item :label="item.label" :prop="item.name">
          <!-- 输入框 -->
          <el-input
            v-model="modelValue[item.name]"
            :placeholder="`请输入${item.label}`"
            clearable
            v-if="item.type === 'input'"
            v-bind="item?.props"
          />

          <!-- 下拉框 -->
          <el-select
            v-model="modelValue[item.name]"
            :placeholder="`请选择${item.label}`"
            clearable
            v-if="item.type === 'select'"
            v-bind="item?.props"
          >
            <el-option
              v-for="option in item!.props!.option"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <!-- 插槽 -->
          <slot v-if="item.type === 'slot'" :name="item.name" :form="modelValue" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import type { WFormPros } from '@/types/WLib'
import { FormInstance } from 'element-plus'

const props = withDefaults(defineProps<WFormPros>(), {
  labelWidth: '80px',
  formSize: 'large',
})

const { validateSuccess } = props
const { modelValue, labelWidth, formConfig, formSize, formRules } = toRefs(props)

const form = ref<FormInstance>()

const validate = () => {
  form.value
    ?.validate()
    .then(() => {
      validateSuccess?.()
    })
    .catch(() => {
      console.log('error')
    })
}

defineExpose({
  validate,
})
</script>

<style lang="scss" scoped></style>
